package batch_processor

import (
	"alarm_service/common/logger"
	"alarm_service/internal/db"
	"alarm_service/internal/models"
	"github.com/robfig/cron/v3"
	"gorm.io/gorm"
	"time"
)

type BatchProcessor struct {
	c  *cron.Cron
	DB *gorm.DB
}

func NewBatchProcessor(db *db.DB) *BatchProcessor {
	//loc, _ := time.LoadLocation("Asia/Shanghai")
	b := &BatchProcessor{
		c:  cron.New(cron.WithSeconds()),
		DB: db.DB,
	}
	return b
}

func (b BatchProcessor) Init() {
	now := time.Now()
	oldTime := now.Add(-6 * time.Minute)
	spec := "*/30 * * * * *"
	b.c.AddFunc(spec, func() {
		if err := b.DB.Model(models.Device{}).Where("status = ? and heartbeats_at <= ?", models.DeviceStatusOnline, oldTime).Updates(map[string]interface{}{
			"status":       models.DeviceStatusOffline,
			"p_updated_at": now,
		}).Error; err != nil {
			logger.Errorf("[BatchProcessor] update Device error: %s", err.Error())
		}
	})
	b.c.Start()
}

func (b BatchProcessor) Shutdown() {
	logger.Global().Infof("[BatchProcessor] starting shutdown cronjob")
	b.c.Stop()
}
